import Events from '@/plugins/event';
import {
	SOCKET_HOST
} from '@/config';

class webScoket extends Events {
	options = {}

	constructor(uri) {
		super()
		this.isConnected = false //socket连接记录
		this.timer = null //心跳定时器
		this.uri = uri
		this.url = `${SOCKET_HOST}/websocket/${uri}`
		// this.url = `${SOCKET_HOST}`;
		this.ws = uni.connectSocket({
			url: this.url,
			// url: 'ws://192.168.1.24:8080',
			success(res) {
				console.log('链接成功')
				console.log(res)
			},
			fail(err) {
				console.log('链接失败')
				console.error(err)
			},
			complete: () => {}
		});

		this.ws.onOpen(res => {
			console.log(`WebSocket 已连接:${this.url}`)
			this.isConnected = true;
			/* this.send({
				msg: this.uri
			}) */
			clearInterval(this.timer);
			this.timer = setInterval(() => {
				if (this.isConnected) {
					const msg = JSON.stringify({
						"code": 200,
						"topic": 'heart',
						'title': '保持连接'
					})
					this.send({
						msg
					})
				}
			}, 40000)
		});
		this.ws.onMessage(res => {

			console.log(res)
			// const msg = JSON.stringify({
			// 	"code": 200,
			// 	"topic": this.uri
			// })
			// this.send({
			// 	msg
			// }) //告诉后台推送已收到

			this.onPublish(this.uri, JSON.parse(res.data))
		});
		this.ws.onClose(res => {
			console.warn('WebSocket 已断开')
			this.isConnected = false;
		});
	}

	close() {
		return new Promise((resolve, reject) => {
			if (this.isConnected) {
				clearInterval(this.timer);
				this.ws.close()
			}
			resolve()
		})
	}

	send(data) {
		// console.log(data)
		this.ws.send({
			data: data.msg
		})
		/* 	console.log(data.msg)
			this.ws.send(data.msg) */
		// console.log(`发送${JSON.stringify(data)}`)
	}
}

export default webScoket
